package com.wang.store.service.impl;

import com.wang.store.entity.Cart;
import com.wang.store.entity.Product;
import com.wang.store.mapper.CartMapper;
import com.wang.store.mapper.ProductMapper;
import com.wang.store.service.ICartService;
import com.wang.store.service.ex.AccessDeniedException;
import com.wang.store.service.ex.CartNotFoundException;
import com.wang.store.service.ex.InsertException;
import com.wang.store.service.ex.UpdateException;
import com.wang.store.vo.CartVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.smartcardio.CardException;
import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl  implements ICartService {
    /**
     * 购物车的业务层 依赖于购物车持久层和商品持久层
     */
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public void addToCart(Integer uid, Integer pid, Integer amount, String username) {
        Cart result = cartMapper.findByUidAndPid(uid, pid);
        if (result==null){
            //这个商品从来没有添加过
            Cart cart = new Cart();
           //参数传递的数据

            cart.setUid(uid);
            cart.setPid(pid);
            cart.setNum(amount);
            //补全价格
            Product byId = productMapper.findById(pid);
            cart.setPrice(byId.getPrice());
            //补全四项数据
            cart.setCreatedTime(new Date());
            cart.setModifiedTime(new Date());
            cart.setCreatedUser(username);
            cart.setModifiedUser(username);

            Integer row = cartMapper.insert(cart);
            if (row !=1) {
                throw new InsertException("插入时产生了未知异常");
            }
        }else {
            //当前商品已经存在 更新 商品的数据的num数量
          Integer num = result.getNum()+amount;
            Integer integer = cartMapper.updateNumByCid(
                    result.getCid(),
                    num,
                    username,
                    new Date()
            );
            if (integer!=1){
                throw new UpdateException("更新时产生了未知异常");
            }

        }


    }

    @Override
    public List<CartVO> getVOByUid(Integer uid) {

        return cartMapper.findVOByUid(uid);
    }

    @Override
    public Integer addNum(Integer cid, Integer uid, String username) {
        Cart byCid = cartMapper.findByCid(cid);
        if (byCid==null){
            throw new CartNotFoundException("数据不存在");
        }
        if (!byCid.getUid().equals(uid)){
            throw new AccessDeniedException("非法数据异常");
        }

            Integer num=  byCid.getNum()+1;

        Integer rows = cartMapper.updateNumByCid(cid, num, username, new Date());

        if (rows!=1){
            throw  new UpdateException("插入时产生了未知异常");
        }


        return num;
    }
}
